package concurrecy.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

class SemaphoreTask implements Runnable {
    private Semaphore semaphore;
    private static int count = 0;
    private final int id = count ++;

    public SemaphoreTask(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public String toString() {
        return "Task" + id;
    }

    @Override
    public void run() {
        try {
            System.out.println(this + " ready acquire semaphore");
            semaphore.acquire();
            System.out.println(this + " acquire a semaphore");
            try {
                TimeUnit.SECONDS.sleep(1);
            } finally {
                semaphore.release();
                System.out.println(this + " release a semaphore");
            }
        } catch (InterruptedException e) {
            System.out.println(this + " interrupted");
        }
    }
}

/**
 * 信号量
 */
public class SemaphoreDemo {
    public static void main(String[] args) throws InterruptedException {
        final Semaphore semaphore = new Semaphore(10);
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < 100; i++) {
            service.execute(new SemaphoreTask(semaphore));
        }
        TimeUnit.SECONDS.sleep(5);
        System.out.println("shutdown");
//        service.shutdownNow();
        service.shutdown();
    }
}
